<template>
  <div style="width: 80%; margin: 0 auto;padding: 0 0 60px 0">
    <div id="com-detail" class="basic-box" style="margin: 20px auto;">
      <div class="edit-button"><el-button icon="el-icon-edit" style="right: 0" type="primary" @click="editBasicInfo">编辑</el-button></div>
      <div class="com-detail">
        <div style="display: flex;flex-direction: row;">
          <el-image class="com-icon" :src="company.logo" />
          <div style="display: flex;flex-direction: column;margin: 10px;width: calc(100% - 120px)">
            <div class="com-name">{{ company.name }}</div>
            <div class="text-info" style="display: flex;flex-direction: row;margin: 5px">
              <div class="com-detail text-info">{{ company.label }}</div>
            </div>
            <div class="text-info" style="margin: 10px" v-html="company.intro" />
          </div>
        </div>
      </div>
    </div>
    <div id="hr-list" class="basic-box">
      <div class="text-primary" style="font-weight: bold;margin-bottom: 20px">招聘人信息 <i class="el-icon-watch" /></div>
      <div class="edit-button"><el-button icon="el-icon-circle-plus-outline" type="primary" @click="addHr">添加</el-button></div>
      <div v-for="(item, index) in hrList" :key="index" class="hr">
        <div style="display: flex;flex-direction: row;align-items: center;height: 60px;justify-content: space-between;">
          <div style="display: flex;flex-direction: row;align-items: center;height: 60px">
            <el-image class="hr-avatar" :src="item.avatar" />
            <div class="" style="display: flex;flex-direction: column">
              <div class="hr-name">{{ item.name !== null && item.name.length > 0 ? item.name:item.username }}</div>
              <div class="text-info" style="display: flex;flex-direction: row;align-items: center;line-height: 20px">
                <!--                <div class="hr-detail">{{ item.label }}</div>-->
                <div class="hr-detail">-----HR的标签（后续开发）-----</div>
              </div>
            </div>
          </div>
          <div>
            <el-button type="primary" icon="el-icon-chat-dot-round" circle plain />
            <el-button type="danger" icon="el-icon-delete" circle plain @click="deleteHr(item.username)" />
          </div>
        </div>
        <div style="width: 99%;margin: 5px auto"><el-divider><span class="text-primary" /></el-divider></div>
      </div>
      <div><pagination :total="listQuery.hr.total" :page.sync="listQuery.hr.page" :limit.sync="listQuery.hr.limit" /></div>
    </div>
    <div id="position-list" class="basic-box">
      <div class="text-primary" style="font-weight: bold;margin-bottom: 20px;">招聘岗位 <i class="el-icon-watch" /></div>
      <div class="edit-button"><el-button icon="el-icon-circle-plus-outline" type="primary" @click="addPosition">添加</el-button></div>
      <div class="positions">
        <div v-for="(item, index) in positions" :key="index" class="position-item" @click="toPositionDetail(item.id)">
          <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;width: 100%;">
            <div style="display: flex;flex-direction: column;align-items: flex-start;justify-content: flex-start">
              <div class="position-item-name text-danger">
                {{ item.name }}
              </div>
              <div class="position-item-detail text-info">
                <span class="position-detail">{{ item.label }}</span>
              </div>
            </div>
            <div style="display: flex;flex-direction: column;align-items: center;justify-content: flex-start" class="text-warning position-item-wage">
              {{ item.wageMin !== item.wageMax ? item.wageMin + '-' : '' }} {{ item.wageMax }} 元/月
            </div>
          </div>
        </div>
      </div>
      <div><pagination :total="listQuery.position.total" :page.sync="listQuery.position.page" :limit.sync="listQuery.position.limit" /></div>
    </div>
    <el-dialog title="编辑公司信息" :visible.sync="basicInfoDialogVisible" style="padding: 0">
      <el-form label-position="left" :model="basicInfoTemp" :rules="basicInfoRules" label-width="100px">
        <el-form-item label="公司logo" prop="logo">
          <div @mouseover="comLogoHovering = true" @mouseout="comLogoHovering = false" @click="imageCropper.visible = true" style="width: 100px;height: 100px">
            <el-image class="com-icon" :src="basicInfoTemp.logo"/>
            <div v-show="comLogoHovering" class="com-icon-mask">
              <span style="color: white">更换公司logo</span>
            </div>
          </div>
          <el-input v-model="basicInfoTemp.logo" type="hidden" />
        </el-form-item>
      </el-form>
      <el-form class="form" ref="basicInfoTemp" :model="basicInfoTemp" :rules="basicInfoRules" label-position="left" label-width="100px">
        <el-form-item label="公司名" prop="name">
          <el-input v-model.trim="basicInfoTemp.name" />
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="basicInfoTemp.intro" type="textarea" style="max-width: 600px" :autosize="{ minRows: 3, maxRows: 4}" :auto-complete="addressAutoComplete" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="basicInfoDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateBasicInfo">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加HR" :visible.sync="hrDialogVisible" style="max-width: 1000px;margin: 0 auto;">
      <el-form ref="hrForm" class="form" :model="hrTemp" :rules="hrFormRule" label-position="left" label-width="80px">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model.trim="hrTemp.username" placeholder="请输入hr的用户名" />
        </el-form-item>
        <el-form-item label="所在部门:" prop="group">
          <el-input v-model="hrTemp.group" placeholder="hr的标签之一（后续开发）" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hrDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateHrList">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加岗位" :visible.sync="positionDialogVisible">
      <el-form class="form" :model="positionTemp" ref="positionForm" :rules="positionFormRules" label-position="left" label-width="90px">
        <el-form-item label="工作名称" prop="name">
          <el-input v-model.trim="positionTemp.name" />
        </el-form-item>
        <el-form-item label="工作类型" prop="type">
          <el-cascader
            v-model="positionTemp.type"
            :options="positionOption"
            class="filter-item"
            :props="{
              children:'children',
              label:'name',
              value:'name'
            }"
            placeholder="职位类型"
            clearable
          />
        </el-form-item>
        <el-form-item label="薪酬" prop="wage">
          <el-input v-model.number="positionTemp.wageMin" style="width: 100px" />
          ~
          <el-input v-model.number="positionTemp.wageMax" style="width: 100px" />
          <el-input v-model="positionTemp.wage" type="hidden" style="width: 100px" />
        </el-form-item>
        <el-form-item label="负责HR" prop="hr">
          <el-select v-model="positionTemp.hr" placeholder="请选择">
            <el-option v-for="(item,index) in hrList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作地区" prop="region">
          <el-cascader
            v-model="positionTemp.region"
            class="filter-item"
            :options="provinces"
            :props="{children:'city',label:'name',value:'name'}"
            placeholder="地区"
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-autocomplete
            v-model="positionTemp.address"
            class="inline-input"
            :fetch-suggestions="aMapSearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            style="width: 500px"
            :disabled="positionTemp.region.length <= 1"
            @select="selectAddress"
          >
            <template slot="prepend" v-if="positionTemp.region.length > 1"> {{ positionTemp.region[0] + (positionTemp.region[0] !== positionTemp.region[1] ? positionTemp.region[1] : '') }}</template>
            <template slot-scope="{ item }">
              <div class="name">{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="岗位描述" prop="description">
          <div class="editor-content" v-html="positionTemp.description">
          </div>
          <tinymce v-model="positionTemp.description" height="200" @change="descriptionChange" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="positionDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updatePosition">
          确定
        </el-button>
      </div>
    </el-dialog>
    <image-cropper
      v-show="imageCropper.visible"
      :key="imageCropper.key"
      :width="300"
      :height="300"
      url="http://localhost:8090/"
      :headers="{authorization:'+ $store.getters.token +'}"
      lang-type="zh"
      @close="imageCropper.visible = false"
      @crop-upload-success="cropSuccess"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { provinces } from '@/utils/provinceCity'
import Tinymce from '@/components/Tinymce'
import { checkUsername, getHrList, addHrRoleToUserByName, checkUserCom, deleteHrRoleToUserByName } from '@/api/user'
import { fetchComInfoByToken, updateCom, checkComNameBeforepdate } from '@/api/com'
import { getPositionByCid, getPositionOption, updatePosition } from '@/api/position'
import { MessageBox } from 'element-ui'
import ImageCropper from '@/components/ImageCropper'

export default {
  name: 'MyCompany',
  components: { ImageCropper, Pagination, Tinymce },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === null || value.length <= 0) {
        callback(new Error('用户名不能为空'))
      } else {
        checkUsername(value).then(
          res => {
            if (res.data) {
              checkUserCom(value).then(
                res2 => {
                  if (!res2.data) {
                    callback()
                  } else {
                    callback(new Error('用户已经加入了其他公司，请联系用户或客服'))
                  }
                }
              )
            } else {
              callback(new Error('用户不存在'))
            }
          }
        )
      }
    }
    const validateComName = (rule, value, callback) => {
      if (value === null || value.length <= 0) {
        callback(new Error('公司名不能为空'))
      } else {
        checkComNameBeforepdate(value, this.company.id).then(
          res => {
            if (res.data) {
              callback(new Error('公司名重名，请联系管理员或现公司名用户'))
            } else {
              callback()
            }
          }
        )
      }
    }
    const validateWage = (rule, value, callback) => {
      if (this.positionTemp.wageMin === null || this.positionTemp.wageMin.length <= 0 || this.positionTemp.wageMax === null || this.positionTemp.wageMax.length <= 0) {
        callback(new Error('薪酬不能为空'))
      } else if (this.positionTemp.wageMin > this.positionTemp.wageMax){
        callback(new Error('最低薪酬不能大于最高薪酬'))
      }
      callback()
    }
    const validateDescription = (rule, value, callback) => {
      if (this.positionTemp.description === null || this.positionTemp.description.length <= 0){
        callback(new Error('岗位描述不能为空'))
      }
      callback()
    }
    return {
      aMap: null,
      comLogoHovering: false,
      imageCropper: {
        visible: false,
        key: 0,
        image: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191'
      },
      addressAutoComplete: '',
      region: null,
      provinces,
      positionOption: [],
      basicInfoDialogVisible: false,
      hrDialogVisible: false,
      positionDialogVisible: false,
      activeApplicant: -1,
      hrTemp: {
        username: '',
        group: ''
      },
      hrFormRule: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }]
      },
      positionTemp: {
        region: [],
        name: '',
        type: '',
        hr: '',
        address: '',
        wageMin: '',
        wageMax: '',
        description: `<p><strong>此处填写岗位的详细描述，上方是预览</strong></p> <p><strong>例：</strong></p> <p><strong>职位描述：</strong></p> <ol> <li>负责相关APP产品的用户体验、UI设计工作；</li> <li>主动性强，能主动探索新方案，推动方案执行和实施；</li> <li>参与设计优化、沉淀设计方法、制定规范；</li> </ol> <p><strong>职位要求:</strong></p> <ul> <li>作品需具有UI设计案例；</li> <li>具备一定的手绘能力；</li> <li>思维缜密，逻辑性强，同时具有良好沟通能力、善于对设计进行表达</li> <li>对视觉设计、色彩有敏锐的观察能力及分析能力；</li> <li>具有抗压能力、责任心；</li> <li>简历请附上作品或作品链接；</li> <li>每周实习4天或以上，实习期至少4个月及以上，长期实习优先。</li> </ul>`
      },
      positionFormRules: {
        name: [
          { required: true, trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        wage: [{ validator: validateWage, required: true, trigger: 'change' }],
        region: [{ required: true, trigger: 'change' }],
        type: [{ required: true, trigger: 'blur' }],
        hr: [{ required: true, trigger: 'change' }],
        address: [{ required: true, trigger: 'blur' }],
        description: [{ validator: validateDescription, trigger: 'change' }]
      },
      basicInfoTemp: {
        name: '',
        logo: '',
        description: ``
      },
      basicInfoRules: {
        name: [{ required: true, trigger: 'blur', validator: validateComName }],
        intro: [{ required: true, trigger: 'blur' }]
      },
      company: {
        id: -1,
        name: '网易',
        logo: '',
        description: '网易 (NASDAQ: NTES)，1997年由丁磊先生在广州创办、2000年在美国NASDAQ股票交易所挂牌上市，是中国领先的互联网技术公司，在开发互联网应用、服务等方面始\n' +
          '              终保持中国业界领先地位。本着对中国互联网发展强烈的使命感，缔造美好生活的愿景，网易利用最先进的互联网技术，加强人与人之间信息的交流和共享，为海量用户提供\n' +
          '              优质的产品和服务，始终秉持着"以匠心、致创新"的理念，通过科技创新改变生活。'
      },
      hrList: [],
      positions: [],
      listQuery: {
        hr: {
          cid: -1,
          total: 10,
          page: 1,
          limit: 5
        },
        position: {
          cid: -1,
          total: 10,
          page: 1,
          limit: 5
        }
      }
    }
  },
  mounted() {
    this.getDetail()
    getPositionOption().then(res => { this.positionOption = res.data.items })
  },
  methods: {
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.basicInfoTemp.logo = resData
    },
    aMapSearch(queryString, cb) {
      const prefix = this.positionTemp.region[0] + (this.positionTemp.region[0] !== this.positionTemp.region[1] ? this.positionTemp.region[1] : '')
      const keyword = prefix + this.positionTemp.address
      AMap.plugin('AMap.Autocomplete', function() {
        var autoOptions = {
          city: '全国',
          input: 'address'
        }
        var autoComplete = new AMap.Autocomplete(autoOptions)
        autoComplete.search(keyword, function(status, result) {
          console.log(result)
          const tips = result.tips
          for (const i in tips) {
            if (tips[i].name.indexOf(prefix) >= 0) {
              tips[i].name = tips[i].name.substring(tips[i].name.indexOf(prefix) + prefix.length)
            }
          }
          cb(result.tips)
        })
      })
    },
    selectAddress(item) {
      const prefix = this.positionTemp.region[0] + (this.positionTemp.region[0] !== this.positionTemp.region[1] ? this.positionTemp.region[1] : '')
      this.positionTemp.address = item.district.substring(item.district.indexOf(prefix) + prefix.length)  + item.address + item.name
    },
    updatePosition() {
      this.$refs.positionForm.validate(
        valid => {
          const form = Object.assign({ cid: this.company.id }, this.positionTemp)
          form.address = this.positionTemp.region[0] + (this.positionTemp.region[0] !== this.positionTemp.region[1] ? this.positionTemp.region[1] : '') + form.address
          updatePosition(form).then(
            res => {
              if (res.status === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 400
                })
                this.positionDialogVisible = false
                this.getDetail()
              }
            }
          )
        }
      )
    },
    getDetail() {
      const self = this
      fetchComInfoByToken(self.id).then(
        orgRes => {
          self.company = orgRes.data.items
          self.listQuery.hr.cid = self.company.id
          self.listQuery.position.cid = self.company.id
          getHrList(self.listQuery.hr).then(
            HrRes => {
              self.hrList = HrRes.data.items
              self.listQuery.hr.total = HrRes.data.total
              getPositionByCid(self.listQuery.position).then(
                posRes => {
                  self.positions = posRes.data.items
                  self.listQuery.position.total = posRes.data.total
                }
              )
            }
          )
        }
      )
    },
    editBasicInfo() {
      this.basicInfoDialogVisible = true
      this.basicInfoTemp = Object.assign({}, this.company)
    },
    updateBasicInfo() {
      this.$refs.basicInfoTemp.validate(
        valid => {
          if (valid) {
            const form = Object.assign({}, this.basicInfoTemp)
            updateCom(form).then(
              res => {
                if (res.status === 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 500
                  })
                  this.basicInfoDialogVisible = false
                  this.getDetail()
                }
              }
            )
          }
        }
      )
    },
    addHr() {
      this.hrDialogVisible = true
    },
    deleteHr(username) {
      const self = this
      MessageBox.confirm('确定删除该HR？', {
        confirmButtonText: '删除',
        confirmButtonClass: 'danger-button',
        cancelButtonText: '返回',
        type: 'error',
        beforeClose: action => {
          console.log(action)
          if (action === 'confirm') {
            deleteHrRoleToUserByName({ username }).then(
              res => {
                if (res.status === 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 500
                  })
                  self.getDetail()
                }
              }
            )
          }
          MessageBox.close()
        }
      })
    },
    updateHrList() {
      const self = this
      this.$refs.hrForm.validate(
        valid => {
          if (valid) {
            const form = { username: self.hrTemp.username, cid: self.company.id }
            addHrRoleToUserByName(form).then(
              res => {
                if (res.status === 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 400
                  })
                  this.hrDialogVisible = false
                }
              }
            )
          }
        }
      )
    },
    addPosition() {
      this.positionDialogVisible = true
    },
    toPositionDetail(id) {
      this.$router.push('myPositionDetail/' + id)
    },
    descriptionChange(event) {
      console.log(event)
    },

  }
}
</script>

<style scoped lang="scss">
.edit-button{
  float: right;
  align-self: flex-end;
  position: absolute;
}
.basic-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 10px 20px;
}
.com-detail{
  display: flex;
  flex-direction: row;
  align-items: center;
  .com-icon{
    width: 100px;
    height: 100px;
  }
  .com-name{
    font-size: 25px;
    font-weight: bold;
    margin: 0 10px;
  }
  .com-detail{
    margin-left: 5px;
  }
}
.hr{
  margin: 10px 0;
  .hr-avatar{
    margin-right: 15px;
    width: 35px;
    height: 35px;
  }
  .hr-name{
    font-size: 22px;
  }
  .hr-detail{
    margin:5px 5px 0 0;
  }
}
.inner-html{
  line-height: 30px;
  padding: 10px;
}
.map{
  width: 50%;
  height: 200px;
  margin: 20px;
}
.el-divider--horizontal{
  margin: 0;
}
.pagination-container{
  margin: 0;
  padding: 0;
}
.position-item{
  border: none;
  height: 100px;
  width: 100%;
}
.el-input{
  width: 300px;
}
.editor-content{
  margin: 0 0 20px;
  padding: 10px;
  height: 300px;
  overflow: auto;
  border: 1px solid #AAAAAA;
  line-height: 20px;
}
.danger-button{
  background-color:#F56C6C;
}
.com-icon-mask{
  position: absolute;
  top: 0;
  z-index: 99;
  width: 100px;
  height: 100px;
  opacity:80%;
  background-color: rgba(83, 93, 102, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
</style>
